<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }} {{ bookName }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="页面名称">
            <a-input v-decorator="['name']" placeholder="请输入页面名称" />
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>
      </a-row>
      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <a-button type="primary" @click="goBack">返回</a-button>
        <a-button type="primary" icon="plus" @click="handleCreate">创建二维码</a-button>
        <a-button type="primary" icon="plus" v-if="canBatchPage" @click="handleAddBatchPage(null)"
          >批量编辑页面</a-button
        >
        <a-button type="primary" icon="plus" v-if="canAddNullPage" @click="handleAddBatchNullPage(null)"
          >追加空页面</a-button
        >
        <a-button type="primary" icon="plus" v-if="isNodeImage" @click="handleCoverPage(null)">同步全覆盖页面</a-button>
        <a-button type="primary" v-if="canSync" @click="handleSync">同步文件</a-button>
        <a-button type="primary" v-if="isNodeImage" @click="handleSyncNodeFile">同步节点文件</a-button>
      </div>
    </div>
    <s-table ref="table" rowKey="id" :loading="isLoading" :columns="columns" :data="loadData" :pageSize="15">
      <span slot="url" slot-scope="text, item">
        <a-button class="fl-l" type="primary" icon="copy" @click="handleCopy(text)">点击复制</a-button>
      </span>
      <span slot="qrcode" slot-scope="text, item">
        <qrcodeImg :content="item.url" />
      </span>
      <span slot="status" slot-scope="text, item">
        <a-tag class="cur-p" :color="text === 10 ? 'green' : 'red'" @click="handleUpdateStatus(item.id, text)">{{
          text === 10 ? '正常' : '停用'
        }}</a-tag>
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="text, item">
        <a v-action:edit @click="handleEdit(item)">编辑</a>
      </span>
    </s-table>
    <PageForm ref="Form" :bookId="bookId" :actionType="actionType" @handleSubmit="handleRefresh(false)" />
    <BatchAddNullPage ref="nullPage" @handleSubmit="handleRefresh(false)" />
    <makeCode ref="makeCode" />
    <sync ref="syncForm" @handleSubmit="handleRefresh(false)" />
  </a-card>
</template>

<script>
import * as Api from '@/api/book/page'
import { STable } from '@/components'
import PageForm from '@/views/book/modules/PageForm'
import BatchAddNullPage from '@/views/book/modules/BatchAddNullPage'
import qrcodeImg from '@/views/book/modules/qrcodeImg'
import makeCode from '@/views/book/modules/makeCode'
import WorkTypeEnum from '@/common/enum/workType'
import sync from '@/views/book/modules/sync'
/** @var {BookActionType} BookActionType */
import BookActionType from '@/common/enum/bookActionType'
import { detail } from '@/api/book'

export default {
  name: 'Index',
  components: {
    STable,
    PageForm,
    qrcodeImg,
    makeCode,
    sync,
    BatchAddNullPage
  },
  computed: {
    canBatchPage() {
      return (
        [BookActionType.VIDEO.value, BookActionType.IMAGE_NODE_LOCAL.value, BookActionType.IMAGE_NODE.value].indexOf(
          this.actionType
        ) > -1
      )
    },
    canSync() {
      return [BookActionType.DICTIONARY.value, BookActionType.IMAGE_NODE.value].indexOf(this.actionType) > -1
    },
    isNodeImage() {
      return [BookActionType.IMAGE_NODE_LOCAL.value, BookActionType.IMAGE_NODE.value].indexOf(this.actionType) > -1
    },
    canAddNullPage() {
      return (
        [
          BookActionType.DICTIONARY.value,
          BookActionType.AUDIO.value,
          BookActionType.IMAGE_NODE_LOCAL.value,
          BookActionType.IMAGE_NODE.value
        ].indexOf(this.actionType) > -1
      )
    }
  },
  data() {
    return {
      BookActionType,
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      bookId: 0,
      bookName: '',
      actionType: -1,
      // 表头
      columns: [
        {
          title: '名称',
          dataIndex: 'name'
        },

        {
          title: '页面Url',
          dataIndex: 'url',
          scopedSlots: { customRender: 'url' }
        },
        {
          title: '二维码',
          dataIndex: 'qrcode',
          scopedSlots: { customRender: 'qrcode' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (param) => {
        return Api.list({ ...param, ...this.queryParam, bid: this.bookId }).then((response) => response.data.list)
      }
    }
  },
  created() {
    this.bookId = this.$route.query.bookId
    this.bookName = this.$route.query.bookName
    this.queryParam.bookId = this.bookId
    this.getBookInfo()
  },
  methods: {
    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */

    // 修改状态()
    handleUpdateStatus(id, state) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要' + (state === 10 ? '停用' : '启用') + '该记录吗?',
        onOk() {
          return Api.changeStatus({ id })
            .then((result) => {
              // 显示成功
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    getBookInfo() {
      detail({ id: parseInt(this.bookId) }).then((res) => {
        this.actionType = res.data.tpl_id
      })
    },
    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },
    handleEdit(item) {
      this.$refs.Form.edit(item)
    },
    handleCopy(text) {
      window.getSelection().removeAllRanges()
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      textarea.remove()
      this.$message.success('复制成功', 1.5)
    },
    goBack() {
      this.$router.push({ path: '/book/index' })
    },
    handleCreate() {
      this.$refs.makeCode.open(WorkTypeEnum.PAGE_QR.value, WorkTypeEnum.PAGE_QR_TEXT.value, this.bookId)
    },
    handleSync() {
      this.$refs.syncForm.open(this.bookId, this.actionType)
    },
    handleSyncNodeFile() {
      const app = this
      const modal = this.$confirm({
        title: '您确定要同步节点文件吗?',
        onOk() {
          return Api.syncNodeFile({ bookId: app.bookId, actionType: app.actionType })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.$router.push({
                path: '/book/page/edit',
                query: { bookId: app.bookId, type: app.actionType, bookName: app.bookName }
              })
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    handleAddBatchPage() {
      this.$router.push({
        path: '/book/page/edit',
        query: { bookId: this.bookId, type: this.actionType, bookName: this.bookName }
      })
    },
    handleAddBatchNullPage() {
      this.$refs.nullPage.open(this.bookId, this.actionType)
    },
    handleCoverPage() {
      const app = this
      const modal = this.$confirm({
        title: '您确定要覆盖所有页面吗?',
        content: '请保证资源文件存在且正确，覆盖后所有节点配置将清空,默认开启卡片模式',
        onOk() {
          return Api.coverPage({ bookId: app.bookId, actionType: app.actionType })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}
</style>
